import { h, render } from "vue";
import Xtxmessage from "./message.vue";
type messageType = {
  type: "success" | "error" | "warning";
  text: string;
};
// 在body声明一个div
const div = document.createElement("div");
div.setAttribute("class", "xtx-message-container");
document.body.appendChild(div);

// 声明一个延时器
let timer: number = -1;
// 导出 messsage函数
function Message({ type, text }: messageType, duration: number = 2000) {
  // h函数
  const vNode = h(Xtxmessage, { type }, text);
  // render挂载
  render(vNode, div);
  // 启动延时器3秒后删除虚拟DOM
  // 每次使用前清空延时器
  clearTimeout(timer);
  timer = window.setTimeout(() => {
    // 删除虚拟DOM
    render(null, div);
    // 3秒后删除body内的div
    // setTimeout(() => {
    //   document.body.removeChild(div);
    // }, 3000);
  }, duration);
}
Message.success = (text: string, duration?: number) => {
  Message(
    {
      type: "success",
      text: text,
    },
    duration
  );
};

Message.error = (text: string, duration?: number) => {
  Message(
    {
      type: "error",
      text: text,
    },
    duration
  );
};

Message.warning = (text: string, duration?: number) => {
  Message(
    {
      type: "warning",
      text: text,
    },
    duration
  );
};
export default Message;
